package com.example.healthcode2;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.example.healthcode2.Other.ActivityCollector;

import java.util.HashMap;
import java.util.Map;

public class fillinfoActivity extends AppCompatActivity {
    private EditText text_name, text_number, text_phone, text_city;
    private RadioGroup radioGroup_tem, radioGroup_health, radioGroup_danger;
    private RadioButton radioButton_tem, radioButton_health, radioButton_danger;
    private String name;
    private String fullname, city, phone, number, tem, health, danger;
    private static final int SUBMIT_OK = 7;
    private static final int SUBMIT_ERROR = 8;
    private static final int OTHER = 0;
    private Dialog dialogLoading;
    private Button btn_submit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fillinfo);
        ActivityCollector.addActivity(this);
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        Intent intent = getIntent();
        name = (String) intent.getSerializableExtra("name");
        initview();
    }

    private void initview() {
        text_city = findViewById(R.id.fillinfo_text_city);
        text_name = findViewById(R.id.fillinfo_text_name);
        text_phone = findViewById(R.id.fillinfo_text_phone);
        text_number = findViewById(R.id.fillinfo_text_number);

        radioGroup_tem = findViewById(R.id.fillinfo_rg_tem);
        radioGroup_health = findViewById(R.id.fillinfo_rg_health);
        radioGroup_danger = findViewById(R.id.fillinfo_rg_danger);
        btn_submit = findViewById(R.id.fillinfo_btn_submit);


    }
//提交按钮
    public void submitClick(View view) {
        fullname = text_name.getText().toString();
        city = text_city.getText().toString();
        phone = text_phone.getText().toString();
        number = text_number.getText().toString();

        if (fullname.isEmpty() || city.isEmpty() || phone.isEmpty() || number.isEmpty()) {
            dialogshow("提交失败", "你还有信息没有填写。",false);
            return;
        }
        radioButton_health = findViewById(radioGroup_health.getCheckedRadioButtonId());
        radioButton_tem = findViewById(radioGroup_tem.getCheckedRadioButtonId());
        radioButton_danger = findViewById(radioGroup_danger.getCheckedRadioButtonId());

        tem = radioButton_tem.getText().toString();
        health = radioButton_health.getText().toString();
        danger = radioButton_danger.getText().toString();
        dialogLoadingshow();
        httpRequest();

        btn_submit.setEnabled(false);//使提交按钮无效
    }

    //发送http请求
    private void httpRequest() {

        final RequestQueue queue = Volley.newRequestQueue(this);
        String url = "http://30r97104b2.qicp.vip/user/add";
        final StringRequest request = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        if ("success".equals(s)) {
                            myHandler.sendEmptyMessage(SUBMIT_OK);
                        } else {
                            myHandler.sendEmptyMessage(OTHER);
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        myHandler.sendEmptyMessage(SUBMIT_ERROR);
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("username", name);
                params.put("name1", fullname);
                params.put("id_card", number);
                params.put("phone", phone);
                params.put("address", city);
                params.put("ishot", tem);
                params.put("ishealth", health);
                params.put("isdanger", danger);
                return params;
            }
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);//延时发送
                    queue.add(request);//发送请求
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();


    }


    @SuppressLint("HandlerLeak")
    Handler myHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case SUBMIT_OK:
                    dialogLoading.dismiss();
                    btn_submit.setEnabled(true);//使提交按钮生效
                    dialogshow("提交成功", "提交成功,请重新进入APP", true);
                    break;
                case SUBMIT_ERROR:
                    dialogLoading.dismiss();
                    btn_submit.setEnabled(true);//使提交按钮生效
                    dialogshow("提交失败", "提交失败，请检查网络", false);
                    break;
                case OTHER:
                    dialogLoading.dismiss();
                    btn_submit.setEnabled(true);//使提交按钮生效
                    dialogshow("提交失败", "提交失败，出现未知错误", false);
                    break;
            }
        }
    };

    //加载对话框
    private void dialogLoadingshow() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_loading, null);
        dialogLoading = new AlertDialog.Builder(this, R.style.LoadingDialog).setView(view).create();
        ImageView imageView = view.findViewById(R.id.dialog_img_loading);
        TextView textView = view.findViewById(R.id.dialog_text_loading);
        textView.setText("提交中...");
        Glide.with(this).load(R.drawable.load_0_gif).into(imageView);
        dialogLoading.show();
        Window window = dialogLoading.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        DisplayMetrics dm = getResources().getDisplayMetrics();//获取屏幕分辨率
        int screenWidth = dm.widthPixels;
        int screenHeight = dm.heightPixels;
        params.width = (int) (0.9 * screenWidth);
        params.y = (int) (0.05 * screenHeight);
        window.setAttributes(params);
        window.setGravity(Gravity.TOP);
    }

    //弹出对话框
    private void dialogshow(String a, String s, final boolean code) {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_sign, null);
        final AlertDialog dialog = new AlertDialog.Builder(this, R.style.MyDialog).setView(view).create();//创建dialog 并使用style
        TextView textView = view.findViewById(R.id.dialog_text_sign1);
        TextView textView1 = view.findViewById(R.id.dialog_text_sign0);
        textView1.setText(a);
        textView.setText(s);
        Button button = view.findViewById(R.id.dialog_btn_sign);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (code) {
                    ActivityCollector.finishAll();
                    Intent intent = new Intent(fillinfoActivity.this, FirstActivity.class);
                    startActivity(intent);
                } else {
                    dialog.dismiss();
                }
            }
        });

        dialog.show();
        //需要先显示再设置大小
        Window window = dialog.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        DisplayMetrics dm = getResources().getDisplayMetrics();//获取屏幕分辨率
        int screenWidth = dm.widthPixels;
        int screenHeight = dm.heightPixels;
        params.width = (int) (0.7 * screenWidth);

        window.setAttributes(params);
    }

    //返回按钮按下
    public void fillBackClick(View view) {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }
}
